package cn.talk.doodledemo.slice;

import cn.talk.doodle.ability.base.DoodleActivity;
import cn.talk.doodle.ability.base.DoodleParams;
import cn.talk.doodle.ability.base.DoodleView;
import cn.talk.doodle.dialog.Toast;
import cn.talk.doodle.util.StringUtils;
import cn.talk.doodledemo.ResourceTable;
import cn.talk.doodledemo.utils.FileUtils;
import cn.talk.doodledemo.utils.GifSizeFilter;

import cn.talk.doodledemo.utils.PermissionUtils;
import cn.talk.doodledemo.utils.log.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MatisseAbility;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.filter.Filter;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.bundle.IBundleManager;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileDescriptor;
import java.util.ArrayList;
import java.util.List;

import static cn.talk.doodle.ability.base.DoodleActivity.*;

public class MainAbilitySlice extends AbilitySlice {

    private static final int REQUEST_CODE = 23;
    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 23;
    public static final int REQ_CODE_DOODLE = 101;

    private Text text_helloworld;
    private Text edit_one_picture;
    private Image selected_image;
    private DataAbilityHelper helper;
    private String selectedImagePath;
    private Uri selectedImageUri;

    private Button btn_guide;
    private Button btn_mosaic;
    private Button btn_scale_gesture;


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initView();

        helper = DataAbilityHelper.creator(getContext());
    }

    private void initView() {
        btn_guide = (Button) findComponentById(ResourceTable.Id_btn_guide);
        btn_mosaic = (Button) findComponentById(ResourceTable.Id_btn_mosaic);
        btn_scale_gesture = (Button) findComponentById(ResourceTable.Id_btn_scale_gesture);
        Text chose_picture = (Text) findComponentById(ResourceTable.Id_chose_picture);
        text_helloworld = (Text) findComponentById(ResourceTable.Id_text_helloworld);
        selected_image = (Image) findComponentById(ResourceTable.Id_selected_image);
        edit_one_picture = (Text) findComponentById(ResourceTable.Id_edit_one_picture);

        edit_one_picture.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                System.out.println("Matisse "+ "onClick: ");
                //写死测试
                if (StringUtils.isEmpty(selectedImageUri))
                    selectedImageUri = Uri.parse("dataability:///media/external/images/media/473");

                if (!StringUtils.isEmpty(selectedImagePath)){
                    // 涂鸦参数
                    DoodleParams params = new DoodleParams();
                    params.mIsFullScreen = true;
                    // 图片路径
                    params.mImagePath = selectedImagePath;
                    // 初始画笔大小
                    params.mPaintUnitSize = DoodleView.DEFAULT_SIZE;
                    // 画笔颜色
                    params.mPaintColor = getColor(ResourceTable.Color_red);
                    // 是否支持缩放item
                    params.mSupportScaleItem = true;
                    // 图片Uri
                    params.mImageUriStr = selectedImageUri.getScheme()+":"+selectedImageUri.getDecodedSchemeSpecificPart();
                    System.out.println(selectedImageUri.getDecodedPath() + "  getDecodedPath/  " +
                            selectedImageUri.getEncodedPath() + " getEncodedPath /  " +
                            selectedImageUri.getDecodedHost() + "  getDecodedHost/  " +
                            selectedImageUri.getDecodedSchemeSpecificPart() + "  getDecodedSchemeSpecificPart/  " +
                            selectedImageUri.getScheme() + "  getScheme/  " +
                            selectedImageUri.getLastPath() + "  getLastPath/  " +
                            selectedImageUri.getDecodedAuthority() + "  getDecodedAuthority/  ");
                    // 启动涂鸦页面
                   // DoodleActivity.startActivityForResult(getAbility(), params, REQ_CODE_DOODLE);
                    Intent intent = new Intent();
      /*  Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(activity.getBundleName())
                .withAbilityName(DoodleActivity.class.getName())
                .build();*/
                    Operation operation = new Intent.OperationBuilder()
                            .withAction("ability.intent.QUERY_OPEN_DOODLE")
                            .build();
                    intent.setOperation(operation);
                    intent.setParam(KEY_PARAMS, params);
                    startAbilityForResult(intent, REQ_CODE_DOODLE);
                }else{
                    LogUtils.e("selectedImagePath is null");
                    Toast.show("selectedImagePath is null");
                }
            }
        });


        chose_picture.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED ||
                        verifySelfPermission("ohos.permission.CAMERA") != IBundleManager.PERMISSION_GRANTED ||
                        verifySelfPermission("ohos.permission.READ_MEDIA") != IBundleManager.PERMISSION_GRANTED ||
                        verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED ) {
                    if (canRequestPermission("ohos.permission.READ_MEDIA")) {
                        requestPermissionsFromUser(
                                new String[]{"ohos.permission.READ_MEDIA",
                                        "ohos.permission.WRITE_MEDIA",
                                        "ohos.permission.MEDIA_LOCATION",
                                        "ohos.permission.CAMERA",
                                        "ohos.permission.WRITE_USER_STORAGE",
                                        "ohos.permission.READ_USER_STORAGE"
                                }, MY_PERMISSIONS_REQUEST_CAMERA);
                    } else {

                    }
                } else {
                    Matisse.from(MainAbilitySlice.this)
                            .choose(MimeType.ofImage())
                            .showSingleMediaType(true)
                            .addFilter(new GifSizeFilter(320, 320, 20 * Filter.K * Filter.K))
                            .countable(true)
                            .capture(true)
                            .maxSelectable(1)
                            .originalEnable(false)
                            .forResult( REQUEST_CODE);
                }

            }
        });
        btn_guide.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent = new Intent();
// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName("cn.talk.doodledemo")
                        .withAbilityName("cn.talk.doodledemo.guide.DoodleGuideAbility")
                        .build();

// 把operation设置到intent中
                intent.setOperation(operation);
                startAbility(intent);
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);

        if (resultCode != MatisseAbility.RESULT_OK && resultCode != RESULT_OK){
            return;
        }
        if (requestCode == REQUEST_CODE){
            try {
                ArrayList<Uri> uriArrayList = resultData.getSequenceableArrayListParam(MatisseAbility.EXTRA_RESULT_SELECTION);
                ArrayList<String> stringArrayList = resultData.getStringArrayListParam(MatisseAbility.EXTRA_RESULT_SELECTION_PATH);

                if (stringArrayList != null && stringArrayList.size() > 0 && uriArrayList != null
                        && uriArrayList.size() > 0){
                    selectedImagePath = stringArrayList.get(0);
                    selectedImageUri = uriArrayList.get(0);

                    //根据屏幕宽度来设置Dialog的宽度，高度自适应
                    Display display = DisplayManager.getInstance().getDefaultDisplay(this).get();
                    final int screenWidth = display.getRealAttributes().width;
                    final int height = display.getRealAttributes().height - AttrHelper.vp2px(300, this);

                    FileDescriptor filedesc = helper.openFile(uriArrayList.get(0),"r");
                    ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
                    decodingOpts.desiredSize = new Size(screenWidth,height);
                    ImageSource imageSource = ImageSource.create(filedesc,null);

                    PixelMap selectedPic = imageSource.createPixelmap(decodingOpts);
                    selected_image.setPixelMap(selectedPic);

                }

                List<Uri> mSelected;
                mSelected = Matisse.obtainResult(resultData);
                System.out.println("Matisse "+ "mSelected: " + mSelected);


             /*   if (stringArrayList != null && stringArrayList.size() > 0 && uriArrayList != null
                    && uriArrayList.size() > 0){

                    //  dataability:///media/external/images/media/473
                    // /storage/emulated/0/DCIM/Camera/IMG_20210527_145123.jpg
                    System.out.println("Matisse "+ "stringArrayList: " + stringArrayList.toString());
                    // 涂鸦参数
                    DoodleParams params = new DoodleParams();
                    params.mIsFullScreen = true;
                    // 图片路径
                    params.mImagePath = stringArrayList.get(0);

                    // 初始画笔大小
                    params.mPaintUnitSize = DoodleView.DEFAULT_SIZE;
                    // 画笔颜色
                    params.mPaintColor = getColor(ResourceTable.Color_red);
                    // 是否支持缩放item
                    params.mSupportScaleItem = true;
                    // 图片Uri
                    params.mImageUriStr = selectedImageUri.getDecodedPath();
                    // 启动涂鸦页面
                    DoodleActivity.startActivityForResult(getAbility(), params, REQ_CODE_DOODLE);
                }*/

            }catch (Exception e){
                throw new ClassCastException("Class Exception");
            }
        }else if (REQ_CODE_DOODLE == requestCode){

            String newSrcPath = resultData.getStringParam(KEY_IMAGE_PATH);
            if (!StringUtils.isEmpty(newSrcPath)){

                Uri uri =Uri.getUriFromFile(new File(newSrcPath));
                Glide.with(getAbility())
                        .load(uri)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .skipMemoryCache(true)
                        .into(selected_image);

            }


        }



    }
}
